#include "hal_modbus_uart.h"


UART_HandleTypeDef huart2;
uart_t g_modbus_uart;
uint8_t g_modbus_rx_char;

static void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
    /* USER CODE END Error_Handler_Debug */
}

void hal_modbus_uart_init(void)
{
    huart2.Instance = USART2;
    huart2.Init.BaudRate = 4800;
    huart2.Init.WordLength = UART_WORDLENGTH_8B;
    huart2.Init.StopBits = UART_STOPBITS_1;
    huart2.Init.Parity = UART_PARITY_NONE;
    huart2.Init.Mode = UART_MODE_TX_RX;
    huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart2.Init.OverSampling = UART_OVERSAMPLING_16;
    huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
    huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
    huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
    if (HAL_UART_Init(&huart2) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_SetTxFifoThreshold(&huart2, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_SetRxFifoThreshold(&huart2, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
    {
        Error_Handler();
    }
    if (HAL_UARTEx_DisableFifoMode(&huart2) != HAL_OK)
    {
        Error_Handler();
    }

    HAL_UART_Receive_IT(&huart2, &g_modbus_rx_char, 1);

    /* USER CODE BEGIN USART3_Init 2 */
    __HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
    /* USER CODE END USART3_Init 2 */

    HAL_NVIC_SetPriority(USART2_IRQn, 1, 1);
    HAL_NVIC_EnableIRQ(USART2_IRQn);

}

int32_t hal_modbus_uart_write(uint8_t *data, uint32_t data_len)
{   
    if (data == NULL)
        return -1;
    
    HAL_UART_Transmit(&huart2, data, data_len, HAL_MAX_DELAY);
    
    return data_len;
}

int32_t hal_modbus_uart_read(uint8_t *buff, uint32_t buff_len)
{
    return rx_fifo_out(&g_modbus_uart, buff, buff_len);
}


